/*
 * Copyright (C) 2010-2011 Enrique Lara (enrique.posix2.lara@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package app.timetogo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;

import android.content.DialogInterface;
import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import android.widget.ImageView;
import android.widget.Toast;

import app.timetogo.model.Alarm;
import app.timetogo.model.App;

import app.timetogo.util.Constants;

import java.text.MessageFormat;

//XXX check if any alerts relevant to route.
public final class TimeToGo extends Activity {
    private Alarm a = null;
    private NotificationManager notificationMgr;
    private boolean timeToGo = false;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        timeToGo = Constants.ACTION_TIME_TO_GO.equals(getIntent().getAction());

        requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);

        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        setContentView(R.layout.transparent);

        final Uri uri = getIntent().getData();
        a = App.loadAlarm(uri, this);

        notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (a != null) {
            notificationMgr.cancel(a.getId());

            final CharSequence title = getText(timeToGo ? R.string.time_to_go : R.string.nothing_found);

            //XXX            setTitle(title);
            final View view = LayoutInflater.from(this).inflate(R.layout.alarm_dia, null);
            final CharSequence msg = getMsg();

            //                final ImageView icon = (ImageView) view.findViewById(R.id.icon);
            //                icon.setImageResource(android.R.drawable.ic_dialog_info);
            Android.cptxt(view, R.id.alarm_station, a.getStopName());
            Android.cptxt(view, R.id.alarm_label, a.getLabelOrStopName());
            Android.cptxt(view, R.id.alarm_direction, a.getDirectionName());

            //
            final ImageView line = (ImageView) view.findViewById(R.id.alarm_line);
            line.setImageResource(a.getRoute().getImageId());

            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(title);
            builder.setView(view);
            builder.setMessage(msg).setCancelable(false);

            if (timeToGo) {
                builder.setPositiveButton(R.string.snooze, new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog, final int id) {
                            snooze(dialog);
                        }
                    });
            } else {
                builder.setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog, final int id) {
                            retry(dialog);
                        }
                    });
            }

            builder.setNeutralButton(R.string.view_alarm, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        view(dialog);
                    }
                });
            builder.setNegativeButton(R.string.dismiss, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dismiss(dialog);
                    }
                });
            builder.show();

            startKlaxon();
        } else {
            Toast.makeText(this, R.string.time_to_go, Toast.LENGTH_LONG).show();
        }
    }

    private CharSequence getMsg() {
        if (timeToGo) {
            return getTimeToGoMsg();
        } else {
            return getNothingFoundMsg();
        }
    }

    private CharSequence getTimeToGoMsg() {
        final CharSequence msg;
        final int nMatches = getIntent().getExtras().getInt(Constants.N_MATCHES);

        if (nMatches > 1) {
            msg = MessageFormat.format(getText(R.string.time_to_go_matches).toString(), Integer.toString(nMatches));
        } else if (nMatches == 1) {
            msg = MessageFormat.format(getText(R.string.time_to_go_match).toString(), Integer.toString(nMatches));
        } else {
            msg = getText(R.string.time_to_go_wtf);
        }

        return msg;
    }

    private CharSequence getNothingFoundMsg() {
        final int nErrors = getIntent().getExtras().getInt(Constants.N_ERRORS);

        if (nErrors == 0) {
            return getText(R.string.nothing_found_dia);
        } else {
            return getText(R.string.nothing_found_dia_err);
        }
    }

    @Override
    public void onBackPressed() {
        // Don't allow back to dismiss.
        return;
    }

    private void snooze(final DialogInterface dialog) {
        a.startPollingIn(Settings.getSnoozeTimeMinutes(TimeToGo.this));
        //XXX add ongoing msg to cancel snoozed alarm
        dismiss(dialog);
    }

    private void retry(final DialogInterface dialog) {
        a.startPollingNow();
        dismiss(dialog);
    }

    private void view(final DialogInterface dialog) {
        a.gotoView();
        dismiss(dialog);
    }

    private void dismiss(final DialogInterface dialog) {
        dialog.dismiss();

        stopKlaxon();

        TimeToGo.this.finish();
    }

    public void startKlaxon() {
        final Intent intent = new Intent(Constants.ACTION_KLAXON, a.getUri(), this, Klaxon.class);
        startService(intent);
    }

    public void stopKlaxon() {
        final Intent intent = new Intent(Constants.ACTION_KLAXON, a.getUri(), this, Klaxon.class);
        stopService(intent);
    }
}
